package com.zhilehuo.pretask.ui.mine

import android.Manifest
import android.app.AlertDialog
import android.app.DatePickerDialog
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.NumberPicker
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.bumptech.glide.Glide
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.button.MaterialButton
import com.zhilehuo.pretask.R
import com.zhilehuo.pretask.databinding.FragmentMineBinding
import java.util.Calendar

/**
 * @Description: "我的"页面(任务1)
 * @Author: Realnt
 * @Date:
 */
class MineFragment : Fragment() {
    private var _binding: FragmentMineBinding? = null
    private val binding get() = _binding!!
    private val viewModel: MineViewModel by viewModels()

    /* 注册拍照活动的结果回调 */
    private val takePicture = registerForActivityResult(ActivityResultContracts.TakePicture()) { success ->
        if (success) viewModel.tempImageUri?.let { loadImage(it) }
    }

    /* 注册从相册选择图片活动的结果回调 */
    private val pickImage = registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
        uri?.let { loadImage(it) }
    }

    /* 权限处理 */
    private val cameraPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
        if (granted) openCamera() else showPermissionDenied()
    }

    private val storagePermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
        if (granted) openGallery() else showPermissionDenied()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        /* 设置系统状态栏为白色 */
        val window = requireActivity().window
        val windowInsetsController = WindowCompat.getInsetsController(window, window.decorView)
        windowInsetsController.isAppearanceLightStatusBars = true
        windowInsetsController.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        requireActivity().window.statusBarColor = Color.parseColor("#FFFFFF")

        _binding = FragmentMineBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupUI()
        observeViewModel()
    }

    /**
     * @Description: 初始化UI
     * @Param  :
     * @Return  :
     */
    private fun setupUI() {
        with(binding) {
            rbMale.setOnClickListener { viewModel.updateGender(Gender.MALE) }
            rbFemale.setOnClickListener { viewModel.updateGender(Gender.FEMALE) }
            etBirthday.setOnClickListener { showNumberPickerDateDialog() }
            ivAvatar.setOnClickListener { showImagePickerDialog() }
        }
    }

    /**
     * @Description: 数据观察
     * @Param  :
     * @Return  :
     */
    private fun observeViewModel() {
        viewModel.selectedGender.observe(viewLifecycleOwner) { gender ->
            updateGenderButtonStyle(gender)
        }

        viewModel.birthday.observe(viewLifecycleOwner) { date ->
            binding.etBirthday.setText(date)
        }
    }

    /**
     * @Description: 转换性别选择按钮的样式
     * @Param gender : 选择的性别
     * @Return  :
     */
    private fun updateGenderButtonStyle(gender: Gender) {
        with(binding) {
            val (selectedBtn, unselectedBtn) = when (gender) {
                Gender.MALE -> rbMale to rbFemale
                Gender.FEMALE -> rbFemale to rbMale
            }
            setButtonSelectedStyle(selectedBtn, true)
            setButtonSelectedStyle(unselectedBtn, false)
        }
    }

    /**
     * @Description: 设置选中的性别按钮的样式
     * @Param button : 选中的按钮
     * @Param isSelected : 是否选中
     * @Return  :
     */
    private fun setButtonSelectedStyle(button: MaterialButton, isSelected: Boolean) {
        val context = button.context
        val strokeWidthSelected = if (isSelected) {
            context.resources.getDimensionPixelSize(R.dimen.selected_stroke_width) // 2dp
        } else {
            context.resources.getDimensionPixelSize(R.dimen.default_stroke_width) // 1dp
        }

        button.apply {
            setStrokeColorResource(
                if (isSelected) R.color.sea_blue_00A0FF
                else R.color.grey_777777
            )
            strokeWidth = strokeWidthSelected
            // 添加点击动画
            animate().scaleX(0.95f).scaleY(0.95f).setDuration(100).withEndAction {
                animate().scaleX(1f).scaleY(1f).duration = 100
            }
        }
    }

    /**
     * @Description: 显示生日选择(DatePickerDialog版)
     * @Param  :
     * @Return  :
     */
    private fun showDatePickerDialog() {
        val calendar = Calendar.getInstance()
        DatePickerDialog(
            requireContext(),
            { _, y, m, d -> viewModel.setBirthday("$y-${m + 1}-$d") },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        ).show()
    }

    /**
     * @Description: 展示选择设置头像的选项
     * @Param  :
     * @Return  :
     */
    private fun showImagePickerDialog() {
        BottomSheetDialog(requireContext()).apply {
            setContentView(R.layout.bottom_sheet_image_picker)
            findViewById<TextView>(R.id.pick_from_gallery)?.setOnClickListener {
                checkStoragePermission()
                dismiss()
            }
            findViewById<TextView>(R.id.shot_photo)?.setOnClickListener {
                checkCameraPermission()
                dismiss()
            }
            show()
        }
    }

    /**
     * @Description: 显示生日选择(NumberPicker版)
     * @Param  :
     * @Return  :
     */
    private fun showNumberPickerDateDialog() {
        val dialog = AlertDialog.Builder(requireContext()).create()
        val view = layoutInflater.inflate(R.layout.dialog_date_picker, null)

        val yearPicker = view.findViewById<NumberPicker>(R.id.year_picker)
        val monthPicker = view.findViewById<NumberPicker>(R.id.month_picker)
        val dayPicker = view.findViewById<NumberPicker>(R.id.day_picker)

        // 初始化日期
        val (initialYear, initialMonth, _) = parseCurrentDate()

        // 年份设置（1900-当前年份）
        yearPicker.minValue = 1900
        yearPicker.maxValue = Calendar.getInstance().get(Calendar.YEAR)
        yearPicker.value = initialYear

        // 月份设置（带格式化）
        monthPicker.minValue = 1
        monthPicker.maxValue = 12
        monthPicker.displayedValues = (1..12).map { "${it}月" }.toTypedArray()
        monthPicker.value = initialMonth

        // 日期动态更新
        updateDayPicker(dayPicker, initialYear, initialMonth)

        yearPicker.setOnValueChangedListener { _, _, newYear ->
            updateDayPicker(dayPicker, newYear, monthPicker.value)
        }

        monthPicker.setOnValueChangedListener { _, _, newMonth ->
            updateDayPicker(dayPicker, yearPicker.value, newMonth)
        }

        dialog.setView(view)
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定") { _, _ ->
            val selectedYear = yearPicker.value
            val selectedMonth = monthPicker.value
            val selectedDay = dayPicker.value
            viewModel.setBirthday("$selectedYear-$selectedMonth-$selectedDay")
        }
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消") { _, _ ->
            dialog.dismiss()
        }
        dialog.show()
    }

    /**
     * @Description: 获取当前日期
     * @Param  :
     * @Return Triple<Int, Int, Int> : 返回年月日三元组
     */
    private fun parseCurrentDate(): Triple<Int, Int, Int> {
        val currentDate = viewModel.birthday.value?.split("-") ?: listOf()
        return if (currentDate.size == 3) {
            Triple(currentDate[0].toInt(), currentDate[1].toInt(), currentDate[2].toInt())
        } else {
            val calendar = Calendar.getInstance()
            Triple(
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH) + 1,
                calendar.get(Calendar.DAY_OF_MONTH)
            )
        }
    }

    /**
     * @Description: 更新天数选择器
     * @Param dayPicker : 日选择器
     * @Param year : 年
     * @Param month : 月
     * @Return  :
     */
    private fun updateDayPicker(
        dayPicker: NumberPicker,
        year: Int,
        month: Int
    ) {
        val maxDay = getMaxDay(year, month)
        dayPicker.minValue = 1
        dayPicker.maxValue = maxDay
        dayPicker.value = dayPicker.value.coerceAtMost(maxDay)
    }

    /**
     * @Description: 获取某月最大天数
     * @Param year : 要获取日期的年
     * @Param month : 要获取日期的月
     * @Return  :
     */
    private fun getMaxDay(year: Int, month: Int): Int {
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.YEAR, year)
        calendar.set(Calendar.MONTH, month - 1)
        calendar.set(Calendar.DATE, 1)
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
    }

    /**
     * @Description: 检查摄像头权限
     * @Param  :
     * @Return  :
     */
    private fun checkCameraPermission() {
        when {
            ContextCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_GRANTED -> openCamera()
            else -> cameraPermission.launch(Manifest.permission.CAMERA)
        }
    }

    /**
     * @Description: 检查储存权限
     * @Param  :
     * @Return  :
     */
    private fun checkStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            openGallery()
        } else {
            when {
                ContextCompat.checkSelfPermission(
                    requireContext(),
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ) == PackageManager.PERMISSION_GRANTED -> openGallery()
                else -> storagePermission.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
        }
    }

    /**
     * @Description: 打开摄像头
     * @Param  :
     * @Return  :
     */
    private fun openCamera() {
        viewModel.createTempImageUri(requireContext())?.let { uri ->
            takePicture.launch(uri)
        }
    }

    /**
     * @Description: 打开相册
     * @Param  :
     * @Return  :
     */
    private fun openGallery() {
        pickImage.launch("image/*")
    }

    /**
     * @Description: 加载图片
     * @Param uri : 图片Uri
     * @Return  :
     */
    private fun loadImage(uri: Uri) {
        Glide.with(this)
            .load(uri)
            .circleCrop()
            .into(binding.ivAvatar)
    }

    private fun showPermissionDenied() {
        Toast.makeText(context, "权限被拒接, 允许相应权限才能使用完整功能", Toast.LENGTH_SHORT).show()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}